package com.byzk.p2p.admin.fuiou.controller;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.fuiou.config.Config;
import com.byzk.p2p.admin.fuiou.dto.TransferToFreezenDto;
import com.byzk.p2p.admin.fuiou.util.SecurityUtils;
import com.byzk.p2p.admin.fuiou.util.WebUtils;
import com.byzk.p2p.admin.fuiou.util.XmlUtils;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.util.WithdrawStatus;
import com.byzk.p2p.admin.system.dto.Callback;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.service.CallbackService;
import com.byzk.p2p.admin.system.service.MemberService;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserService;

/**
 * 富友提现
 * @author suker
 *
 */

@Controller
@RequestMapping("/fuion/withdraw")
@Scope("prototype")
public class FuionWithdrawController extends BaseController{
	
	@Autowired
	private CallbackService callbackService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserAccountService acctountService;
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private MemberService memberService;
	
	@RequestMapping("/apply")
	public String withdraw(@RequestParam("userId")int userId,@RequestParam("amount") double amount) throws Exception{
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String mchnt_cd=Config.mchnt_cd;
		String mchnt_txn_ssn=DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000);
		User user=userService.getById(userId);
		String login_id=user.getPhone();
		
		UserAccount account=acctountService.getByUserId(user.getId());
		MemberLevel level=memberService.getById(account.getLevel());
		List<WithdrawRecord> recordList=withdrawService.listByDateAndUid(account.getUserId(), DateUtils.formatYearMonth(new Date()));
		Double withdrawFee=0.00;//提现手续费
		if(level.getCount()-recordList.size()<=0){
			withdrawFee=2.00;
		}
		String amt=((int)(amount-withdrawFee)*100)+"";// （提现金额-提现手续费）*100
		String page_notify_url=Config.server_url+"/account/withdraw";
		String back_notify_url=Config.server_url+"/fuion/withdraw/callback";
		String signature=SecurityUtils.sign(amt + "|" + back_notify_url + "|" + login_id+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + page_notify_url);
	    response.setContentType("text/html;charset=UTF-8");

	    List<BankCard> bankList = bankCardService.listCardByUserId(userId);
	    
		WithdrawRecord withdraw = new WithdrawRecord();
		withdraw.setCode(mchnt_txn_ssn);
		withdraw.setUserId(userId);
		withdraw.setCardNo(bankList.get(0).getCardNo());
		withdraw.setMoney(amount);
		withdraw.setBalance(amount-withdrawFee);
		withdraw.setFee(withdrawFee);	
		withdraw.setStatus(WithdrawStatus.APPLY);
		withdraw.setTerminal("PC");
		withdraw.setBankNo(bankList.get(0).getBankName());
		withdraw.setCreateTime(new Date());
		withdrawService.saveOrUpdate(withdraw);
		
	    String Url = Config.withdraw_url;
	    try {
	        out.println("<!DOCTYPE html>");
	        out.println("<html>");
	        out.println("<head>");
	        out.println("<title>Servlet RechargeServlet</title>");
	        out.println("</head>");
	        out.println("<body>");
	        out.println("<form action="+Url+" id=\"frm1\" method=\"post\">");
	        out.println("<input type=\"hidden\" name=\"mchnt_cd\" value=" + mchnt_cd + ">");
	        out.println("<input type=\"hidden\" name=\"mchnt_txn_ssn\" value=" + mchnt_txn_ssn + ">");
	        out.println("<input type=\"hidden\" name=\"login_id\" value=" + login_id + ">");
	        out.println("<input type=\"hidden\" name=\"amt\" value=" + amt + ">");
	        out.println("<input type=\"hidden\" name=\"page_notify_url\" value=" + page_notify_url + ">");
	        out.println("<input type=\"hidden\" name=\"back_notify_url\" value=" + back_notify_url + ">");
	        out.println("<input type=\"hidden\" name=\"signature\" value=" + signature + ">");
	        out.println("</form>");
	        out.println("<script language=\"javascript\">");
	        out.println("document.getElementById(\"frm1\").submit();");
	        out.println("</script>");
	        out.println("</body>");
	        out.println("</html>");
	    } finally {
	        out.close();
	    }	
		return null;
	}
	
	@RequestMapping("/callback")
	public String quickPayCallback(){
		String resp_code=request.getParameter("resp_code");
		String resp_desc=request.getParameter("resp_desc");
		String mchnt_cd=request.getParameter("mchnt_cd");
		String mchnt_txn_ssn=request.getParameter("mchnt_txn_ssn");
        String login_id=request.getParameter("login_id");
		String amt=request.getParameter("amt");
		String signature=request.getParameter("signature");
		
		System.out.println("---------resp_code:"+resp_code);
		System.out.println("---------resp_desc:"+resp_desc);
		System.out.println("---------mchnt_cd:"+mchnt_cd);
		System.out.println("---------mchnt_txn_ssn:"+mchnt_txn_ssn);
		System.out.println("---------login_id:"+login_id);
		System.out.println("---------amt:"+amt);
		
		String str=resp_code + "|" + resp_desc+"|"+ mchnt_cd + "|" + mchnt_txn_ssn+ "|" + login_id+ "|" +amt + "|" +signature;
		
		Callback callback=new Callback("申请提现",str,new Date());
		callbackService.saveOrUpdate(callback);
		
		if("0000".equals(resp_code)){
			List<WithdrawRecord> withdrawList=withdrawService.selectRecordByCode(mchnt_txn_ssn);
			if(withdrawList.size()>0){
				WithdrawRecord record=withdrawList.get(0);
				User user=userService.getUserByPhone(login_id);
				UserAccount account=acctountService.getByUserId(user.getId());
				
				rechargeService.addFundRecord(user.getId(),0.0,record.getBalance(),"PC","提现",FundRecordType.Type.WITHDRAW.index,0.0,account.getBalance()-record.getBalance());
				
/*				//免提现额度
				Double used_money=account.getBalance()-account.getNotUsedMoney();
				
				//未使用金额
				Double not_used_money=account.getNotUsedMoney();
				
				if(record.getMoney()>used_money){//提现金额大于可提现金额
					account.setNotUsedMoney(account.getBalance()-record.getMoney());
				}else {
					account.setNotUsedMoney(account.getBalance()-(used_money-record.getMoney()));
				}*/

				//用户账户表
				account.setTotalAmount(account.getTotalAmount()-record.getMoney());  //21260.69
				account.setBalance(account.getBalance()-record.getMoney());//可用余额  21260.69
				account.setTotalWithdraw(account.getTotalWithdraw()+record.getMoney());//600
				
				acctountService.saveOrUpdate(account);
				
				record.setStatus(WithdrawStatus.SUCCESS);
				withdrawService.saveOrUpdate(record);
				
				if(record.getFee()>0){
					userToPlatform(user.getId(),record.getFee());
				}
			}
		}
		return null;
	}
	
	public String userToPlatform(Integer userId,Double amount) {
		User user=userService.getById(userId);
		TransferToFreezenDto dto=new TransferToFreezenDto();
		dto.setMchnt_cd(Config.mchnt_cd);
		dto.setMchnt_txn_ssn(DateUtils.getFullFormat()+(new Random().nextInt(8999)+1000));
		dto.setOut_cust_no(user.getPhone());
		dto.setIn_cust_no(Config.user_id);
		dto.setContract_no("");
		dto.setRem("提现手续费");
		double amt = BaseUtil.StringToDoubletoFixed2(amount*100);
		dto.setAmt((int)(amt)+"");
		String inputStr=dto.regSignVal();
		dto.setSignature(SecurityUtils.sign(inputStr));
		
		String backStr;
		try {
			backStr = WebUtils.sendHttp(Config.paltform_to_user_url,dto);
			System.out.println(backStr);
			
			Callback callback=new Callback("用户向平台转账",backStr,new Date());
			callbackService.saveOrUpdate(callback);
			
			String resp_code=XmlUtils.getXmlNodeValue(backStr, "resp_code");
			String mchnt_cd=XmlUtils.getXmlNodeValue(backStr, "mchnt_cd");
			if("0000".equals(resp_code) && Config.mchnt_cd.equals(mchnt_cd)){
				System.out.println("支付提现手续费，操作成功");
				UserAccount account=acctountService.getByUserId(userId);
				rechargeService.addFundRecord(userId,0.0,amount,"PC","提现手续费",FundRecordType.Type.WITHDRAW.index,0.0,account.getBalance());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
